<template>
	<div class="system-screen-container">
		<el-dialog v-model="state.isShowDialog" width="769px" center>
			<template #title>
				<div style="font-size: large" v-drag="['.system-screen-container .el-dialog', '.system-screen-container .el-dialog__header']">
					{{ title }}
				</div>
			</template>
			<el-form :model="state.ruleForm" :rules="state.ruleRules" ref="ruleFormRef" label-width="80px">
				<el-form-item label="名称" prop="name">
					<el-input v-model="state.ruleForm.name" placeholder="请输入可视化名称" />
				</el-form-item>
				<el-form-item label="创建者" prop="owner">
					<el-input v-model="state.ruleForm.owner" :disabled="true" placeholder="请输入创建者" />
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel">取 消</el-button>
					<el-button type="primary" @click="onSubmit" :loading="state.loading">保 存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup name="editScreen">
import { reactive, ref, unref, getCurrentInstance } from 'vue';
import { updateScreen, addScreen } from '@/api/screen/list.ts';
import { ElMessage } from 'element-plus';
import { useUserInfosState } from '@/stores/userInfos';

const userInfos = useUserInfosState();

const props = defineProps({
	title: {
		type: String,
		default: () => '',
	},
});

const { proxy } = getCurrentInstance() as any;
const ruleFormRef = ref<HTMLElement | null>(null);
const state = reactive({
	// 是否显示弹出层
	isShowDialog: false,
	loading: false,
	ruleForm: { id: undefined, name: undefined, screenDataJson: undefined, createTime: undefined, deleteTime: undefined, owner: undefined },
	// 表单校验
	ruleRules: {
		name: [{ required: true, message: '可视化名称不能为空', trigger: 'blur' }],
	},
});
// 打开弹窗
const openDialog = (row: any) => {
	state.ruleForm = JSON.parse(JSON.stringify(row));
	state.ruleForm.owner = userInfos.userInfos.username;
	state.isShowDialog = true;
	state.loading = false;
};

// 关闭弹窗
const closeDialog = (row?: object) => {
	proxy.mittBus.emit('onEditScreenModule', row);
	state.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};

// 保存
const onSubmit = () => {
	const formWrap = unref(ruleFormRef) as any;
	if (!formWrap) return;
	formWrap.validate((valid: boolean) => {
		if (valid) {
			state.loading = true;
			if (state.ruleForm.id != undefined && state.ruleForm.id != 0) {
				const newForm: any = {};
				Object.keys(state.ruleForm).forEach((item) => {
					if (item != 'id' && state.ruleForm[item]) {
						newForm[item] = state.ruleForm[item];
					}
				});
				updateScreen(state.ruleForm.id, newForm).then((response) => {
					ElMessage.success('修改成功');
					state.loading = false;
					closeDialog(state.ruleForm); // 关闭弹窗
				});
			} else {
				addScreen(state.ruleForm).then((response) => {
					ElMessage.success('新增成功');
					closeDialog(state.ruleForm); // 关闭弹窗
				});
			}
		}
	});
};

defineExpose({
	openDialog,
});
</script>
